<template>
  <CloudDialog
    v-model:visible="visible"
    :loading="loading"
    title="添加授权"
    :width="480"
    :before-ok="handleOk"
    :before-open="handleOpen"
    :before-close="handleClose">
    <a-spin :loading="loading" class="w-full">
      <a-form ref="formRef" layout="vertical" :model="formState" :rules="rules">
        <a-form-item label="用户账号" hide-asterisk field="user_id">
          <a-select
            v-model="formState.user_id"
            placeholder="请选择"
            allow-search
            @dropdown-reach-bottom="handleReachBottom">
            <a-option
              v-for="item in data"
              :key="item.id"
              :label="item.username"
              :value="item.id" />
          </a-select>
        </a-form-item>
        <a-form-item label="到期时间" hide-asterisk field="expired_at">
          <a-date-picker
            v-model="formState.expired_at"
            format="YYYY-MM-DD"
            value-format="X"
            :disabledDate="
              (current) => dayjs(current).isBefore(dayjs().subtract(1, 'day'))
            "
            class="w-full"
            placeholder="请选择日期" />
        </a-form-item>
        <a-form-item label="备注" hide-asterisk field="remark">
          <a-input
            v-model.trim="formState.remark"
            :max-length="20"
            show-word-limit
            placeholder="请输入备注" />
        </a-form-item>
        <a-form-item label="启用状态" hide-asterisk field="status">
          <a-radio-group v-model="formState.status">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="2">停用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-spin>
  </CloudDialog>
</template>
<script lang="ts" setup>
import type { UserListItem } from '@/apis/model/user'
import { addAdminApiLicenseApi } from '@/apis/modules/authBind'
import { getAdminApiUsersListApi } from '@/apis/modules/user'
import type { CloudFilterBarState } from '@/components/filter-bar/types'
import { type FieldRule, type FormInstance } from '@arco-design/web-vue'
import dayjs from 'dayjs'
interface IEmits {
  (e: 'refresh'): void
}
const emit = defineEmits<IEmits>()
const visible = defineModel<boolean>('visible', { required: true })
const formRef = ref<FormInstance>()
const formState = ref({
  user_id: '',
  expired_at: '',
  remark: '',
  status: 1
})
const rules = computed<Record<string, FieldRule[]>>(() => {
  const res: Record<string, FieldRule[]> = {
    user_id: [{ required: true, message: '请选择用户账号' }],
    expired_at: [{ required: true, message: '请选择到期时间' }]
  }
  return res
})
const params = ref<CloudFilterBarState>({
  order: 'desc',
  sort: 'created_at'
})
const pagination = reactive({
  offset: 0,
  limit: 15,
  total: 0
})

const data = ref<UserListItem[]>([])
const getList = (type: 1 | 2) => {
  getAdminApiUsersListApi({ ...params.value, ...pagination }).then((res) => {
    pagination.total = res?.total || 0
    if (type === 1) return (data.value = res?.list || [])
    data.value = data.value?.concat(res?.list || [])
    console.log('data.value: ', data.value)
  })
}
const handleReachBottom = () => {
  if (pagination.total <= data.value?.length) return
  pagination.offset += 15
  getList(2)
}
const handleOpen = () => getList(1)
const loading = ref(false)
const handleOk = async () => {
  const error = await formRef.value?.validate()
  if (error) return false
  loading.value = true
  const params = {
    ...formState.value,
    expired_at: getEndOfDayTimestamp(+formState.value.expired_at)
  }
  await addAdminApiLicenseApi(params)
    .then(() => {
      ToastUtils.success('操作成功')
      emit('refresh')
    })
    .finally(() => (loading.value = false))
}
const handleClose = () => {
  visible.value = false
}
watch(
  () => visible.value,
  async (v) => {
    await nextTick()
    if (!v) {
      data.value = []
      formRef.value?.resetFields()
      Object.assign(pagination, { offset: 0, limit: 15, total: 0 })
    }
  }
)
</script>

<style lang="less" scoped></style>
